//
//  NetworkContainer.m
//  kismet-frontend
//
//  Created by L. Preston Sego III on 7/28/09.
//  Copyright 2009 Precognition Inc.. All rights reserved.
//

#import "NetworkData.h"


@implementation NetworkData

- (id)init
{
    networkTable = [[NSMutableDictionary alloc] init];
    numOfNetworks = 0;
    return self;
}

- (int)numberOfNetworks
{
    return numOfNetworks;
}

- (void)addNetworkOrUpdate:(NSString *)serverOutput
{
    NSString *returnID;
    NSArray *pieces = [serverOutput componentsSeparatedByString:@" "];
    // pull out the BSSID to see if we already have it
    NSString *bssid = [pieces objectAtIndex:BSSID_BSSID];
    
    // attempt retrieve network from dictionary
    currentNetwork = [networkTable objectForKey:bssid];
    if(currentNetwork == nil)
    {
        // network does not exit - make it
        currentNetwork = [[Network alloc] init];
        numOfNetworks++;
        
        // assign discovery number
        [currentNetwork setDiscoveryID:[NSNumber numberWithInt:numOfNetworks]];
        
        // the BSSID shouldn't change, so we can set it when we add the network
        [currentNetwork setBssid:bssid];
        
        [networkTable setObject:currentNetwork forKey:bssid];
        
        // set our pointer
        _idList[numOfNetworks].net = [networkTable objectForKey:bssid];
        
        
    }
    
    // update all the info
    returnID = [pieces objectAtIndex:SERVER_RESPONSE];
    if([returnID isEqualToString:SSID_RESPONSE])
    {
        [currentNetwork setSsid:   [pieces objectAtIndex:SSID_SSID]];
        [currentNetwork setPackets:[pieces objectAtIndex:SSID_PACKETS]];
    }
    else if([returnID isEqualToString:BSSID_RESPONSE])
    {
        [currentNetwork setChannel:       [pieces objectAtIndex:BSSID_CHANNEL]];
        [currentNetwork setSignal_dbm:    [pieces objectAtIndex:BSSID_SIGNAL_DBM]];
        [currentNetwork setMax_signal_dbm:[pieces objectAtIndex:BSSID_MAX_SIGNAL_DBM]];
        [currentNetwork setFrezMhz:       [pieces objectAtIndex:BSSID_FREQ_MHZ]];
        [currentNetwork setLastTimeSeen:  [pieces objectAtIndex:BSSID_LAST_TIME_SEEN]];
        [currentNetwork setType:          [pieces objectAtIndex:BSSID_TYPE]];
        [currentNetwork setManuf:         [pieces objectAtIndex:BSSID_MANUF]];
    }

}

- (void)deleteNetwork:(NSString*)bssid
{
    // remove from NSDictionary
    [networkTable removeObjectForKey:bssid];
    
    // remove from _idList
    // adjust _sortedList
}

- (Network*)netAtIndex:(unsigned int)index 
{
    if (index >= numOfNetworks   ) return 0;
    return _idList[_sortedList[index]].net;
}

- (unsigned int)nextChangedRow:(unsigned int)lastRow 
{
    unsigned int nxt;
    
    if (lastRow==0xFFFFFFFF) nxt=0;
    else nxt = lastRow + 1;
    
    while (nxt < _sortedCount) {
        if (_idList[_sortedList[nxt]].changed) return nxt;
        nxt++;
    }
    
    return 0xFFFFFFFF;
}

@end
